package mine.code.question.动态规划;

import org.junit.Test;

import java.util.Arrays;

/**
 * 给你两个单词word1 和word2，请你计算出将word1转换成word2 所使用的最少操作数。
 * <p>
 * 你可以对一个单词进行如下三种操作：
 * <p>
 * 插入一个字符
 * 删除一个字符
 * 替换一个字符
 * <p>
 * 示例1：
 * <p>
 * 输入：word1 = "horse", word2 = "ros"
 * 输出：3
 * 解释：
 * horse -> rorse (将 'h' 替换为 'r')
 * rorse -> rose (删除 'r')
 * rose -> ros (删除 'e')
 *
 * @author caijinnan
 */
public class 编辑距离 {

    @Test
    public void run() {
        //"zoologicoarchaeologist"
        //"zoogeologist"
        //"zoologicoarcha"
        //"zoog"
        String word1 = "hooose";
        String word2 = "roo";
        System.out.println(minDistance(word1, word2));
    }

    public int minDistance(String word1, String word2) {
        //dp[i][j] = min(dp[i-1][j]+word1(i)==word2(j),dp[i][j-1]+word1[i]==word2[j]);
        int w1Length = word1.length();
        int w2Length = word2.length();
        int[][] dp = new int[w1Length + 1][w2Length + 1];
        dp[0][0] = 0;
        for (int j = 1; j <= w2Length; j++) {
            dp[0][j] = dp[0][j - 1] + 1;
        }
        for (int i = 1; i <= w1Length; i++) {
            dp[i][0] = dp[i - 1][0] + 1;
        }
        for (int i = 1; i <= w1Length; i++) {
            for (int j = 1; j <= w2Length; j++) {
                char w1 = word1.charAt(i - 1);
                char w2 = word2.charAt(j - 1);
                int iMin = dp[i-1][j]+1;
                int jMin = dp[i][j-1]+1;
                int ijMin = dp[i - 1][j - 1];
                if (w1 != w2) {
                    ijMin = ijMin + 1;
                }
                dp[i][j] = Math.min(Math.min(iMin, jMin), ijMin);
            }
        }
        for (int[] temp : dp) {
            System.out.println(Arrays.toString(temp));
        }
        return dp[w1Length][w2Length];
    }
}
